import {Component, ViewEncapsulation, Input} from '@angular/core';
import {FormGroup, AbstractControl, FormBuilder, Validators} from '@angular/forms';
import {UserService} from '../../services/app.user';
import {Router, ActivatedRoute}  from '@angular/router';
import {EqualPasswordsValidator} from '../../theme/validators';
import {BaThemeSpinner}  from '../../theme/services';
import {Constants} from '../../../app/common/app.constants';
declare let toastr:any;
declare let $:any;
declare let FB:any;

@Component({
    selector: 'passwordreset',
    styleUrls: ['./../login/login.scss'],
    templateUrl: './passwordreset.html',
})


export class Passwordreset {
    @Input()
    constants:Constants;
    form:FormGroup;
    submitted:boolean = false;
    regex:any;
    url:string;
    params:any = {};
    match:string;

    constructor(fb:FormBuilder, private userService:UserService, private router:Router, private route: ActivatedRoute, private spinner:BaThemeSpinner) {
        this.constants = new Constants();
        toastr.options = {positionClass: 'toast-top-right',};
        this.form = fb.group({
            'passwords': fb.group({
                'password': ['', Validators.compose([Validators.required, Validators.minLength(4)])],
                'repeatPassword': ['', Validators.compose([Validators.required, Validators.minLength(4)])]
            }, {validator: EqualPasswordsValidator.validate('password', 'repeatPassword')})
        });
        // this.regex = /[?&]([^=#]+)=([^&#]*)/g;
        // this.url = window.location.hash.toString();
        // this.params = {};
        // while (this.match = this.regex.exec(this.url)) {
        //     this.params[this.match[1]] = this.match[2];
        // }
        this.route.queryParams.subscribe(params => {
            console.log(params);
            
        this.params.user_id = params.user_id;
        this.params.token = params.token;
        });
        
        

    }

    // Function for reset password
    onSubmit(values) {
        this.spinner.showProgress();
        this.submitted = true;
        let data = {
            new_password: values.passwords.password,
            new_password_confirm: values.passwords.repeatPassword,
            token: this.params.token,
            user_id: this.params.user_id
        };

        this.userService.userReset(data).subscribe(
            data => this.loginSucces(data),
            error => this.loginFail(error)
        );

    }

    // Function call after successfully login
    loginSucces(result) {
        this.spinner.hideProgress();
        toastr.success(this.constants.PASSWORDUPDATESUCCESSFULLY);
        this.router.navigate(['login']);
    }

    // Function Call after login fail
    loginFail(error) {
        this.spinner.hideProgress();
        toastr.error(error.error_message);
    }

    // Facebook login when click on button
    onFacebookLoginClick() {
        FB.login(
            (response) => {
            }
        );
    }
}
